package com.cookapp.service;

import com.cookapp.common.exception.BusinessException;
import com.cookapp.common.enums.ResultCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsService {

    private final RedisTemplate<String, String> redisTemplate;
    
    // 验证码在Redis中的前缀
    private static final String SMS_CODE_PREFIX = "sms:code:";
    // 验证码有效期（分钟）
    private static final int SMS_CODE_EXPIRE = 5;

    /**
     * 发送短信验证码
     */
    public void sendSmsCode(String phone) {
        // 生成6位数验证码
        String code = generateCode(6);
        
        // 将验证码保存到Redis
        String key = SMS_CODE_PREFIX + phone;
        redisTemplate.opsForValue().set(key, code, SMS_CODE_EXPIRE, TimeUnit.MINUTES);
        
        // 调用短信服务发送验证码
        sendSms(phone, code);
        
        log.info("短信验证码发送成功，手机号：{}，验证码：{}", phone, code);
    }
    
    /**
     * 校验短信验证码
     */
    public boolean verifySmsCode(String phone, String code) {
        String key = SMS_CODE_PREFIX + phone;
        String savedCode = redisTemplate.opsForValue().get(key);
        
        if (savedCode == null) {
            throw new BusinessException(ResultCode.SMS_CODE_EXPIRED);
        }
        
        if (!savedCode.equals(code)) {
            throw new BusinessException(ResultCode.SMS_CODE_ERROR);
        }
        
        // 验证成功后删除Redis中的验证码
        redisTemplate.delete(key);
        return true;
    }
    
    /**
     * 生成随机验证码
     */
    private String generateCode(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }
    
    /**
     * 发送短信
     */
    private void sendSms(String phone, String code) {
        // TODO: 实际项目中对接短信服务商
        // 这里仅做示例，不实际发送短信
        log.info("模拟发送短信：手机号 {}，验证码 {}", phone, code);
    }
} 